package com.iussoft.demo.tcp;

import com.iussoft.demo.util.ConfigUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @description:
 * @author: Hou Dayu
 * @date: Created in 2020/10/27
 */
public class TcpServiceImpl {

    public void pushTcpService() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String portStr = ConfigUtil.getConfigByKey("tcpPort");
                try {
                    System.out.println("发布TCP服务！");
                    ServerSocket server = new ServerSocket(Integer.parseInt(portStr));
                    System.out.println("以下是访问地址："+ConfigUtil.getWsIp()+":"+portStr);
                    while (true) {
                        Socket socket = server.accept();
                        if (null != socket) {
                            new Thread(new SocketServiceTimer(socket), "socket 服务线程").start();
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private class SocketServiceTimer implements Runnable {

        private Socket socket = null;

        public SocketServiceTimer(Socket socket) {
            this.socket = socket;
        }

        public void run() {
            BufferedReader bufferedReader = null;
            try {
                String strMsg = "";
                if (socket != null && socket.isConnected() && Thread.currentThread().isAlive()
                        && !Thread.currentThread().isInterrupted() && !socket.isClosed()) {
                    //byte[] data = new byte[102400];
                    String mg = null;
                    try {
                        bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
                        StringBuilder sb = new StringBuilder("");
                        while ((mg = bufferedReader.readLine()) != null) {
                            sb.append(mg);
                        }
                        strMsg = sb.toString();
                    }catch (IOException e){
                        return;
                    }
                    Date date = new Date();
                    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String ctime = df.format(date);
                    System.out.println("请求到达,到达时间：" + ctime+"；请求信息为:" + strMsg);
                    StringBuilder sb = new StringBuilder();
                    sb.append("{\"sendTime\":\"请求到达时间：" + ctime+"\","+strMsg.substring(1));
                    //返回值长度
                    byte[] dataByteArr = sb.toString().getBytes("UTF-8");
                    //回写返加报文
                    OutputStream os = socket.getOutputStream();
                    //发送实际数据内容
                    os.write(dataByteArr, 0, dataByteArr.length);
                    os.flush();
                    // 关闭输出流
                    socket.shutdownOutput();
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("未能正确执行：" + e.getMessage());
            } finally {
                // 关闭资源
                try {
                    if(null != bufferedReader) {
                        bufferedReader.close();
                    }
                    if(socket != null){
                        socket.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
